﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace DotNetRepository.Tools
{
    public class ValueLock2<TValueType> where TValueType : struct
    {
        private readonly Dictionary<TValueType,object > _lockers = new Dictionary<TValueType, object>();

        public ValueLocker2 Lock(TValueType value)
        {
            object locker;
            lock (_lockers)
            {
                if (!_lockers.TryGetValue(value, out locker))
                {
                    locker = new object();
                    _lockers.Add(value,locker);
                }
            }
            Monitor.Enter(locker);
            return new ValueLocker2(locker);
        }
    }

    public class ValueLocker2 : IDisposable
    {
        private bool _disposed;
        private readonly object _locker;

        internal ValueLocker2(object locker)
        {
            _locker = locker;
        }

        public void Dispose()
        {
            if (_disposed) return;
            _disposed = true;
            Monitor.Exit(_locker);
        }
    }

    
}
